package org.zebra.file.excel.core;

import cn.hutool.core.collection.CollUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.zebra.common.exception.ResultException;
import org.zebra.common.exception.StatusCode;
import org.zebra.file.excel.SimpleExcel;
import org.zebra.file.excel.annotation.ExportExcel;

import javax.servlet.http.HttpServletResponse;
import java.util.Collection;

/**
 * 处理注解ExportExcel 返回值
 *
 * @author zhanghongbin
 */
public class ExportExcelHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {

    private SimpleExcel simpleExcel;

    public ExportExcelHandlerMethodReturnValueHandler(SimpleExcel simpleExcel) {
        this.simpleExcel = simpleExcel;
    }

    /**
     * 只处理@ResponseExcel 声明的方法
     *
     * @param parameter 方法签名
     * @return 是否处理
     */
    @Override
    public boolean supportsReturnType(MethodParameter parameter) {
        return parameter.getMethodAnnotation(ExportExcel.class) != null;
    }

    /**
     * 处理逻辑
     *
     * @param o                返回参数
     * @param parameter        方法签名
     * @param mavContainer     上下文容器
     * @param nativeWebRequest 上下文
     */
    @Override
    public void handleReturnValue(
            Object o,
            MethodParameter parameter,
            ModelAndViewContainer mavContainer,
            NativeWebRequest nativeWebRequest) {
        HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        ExportExcel exportExcel = parameter.getMethodAnnotation(ExportExcel.class);
        mavContainer.setRequestHandled(true);
        if (o instanceof Collection) {
            Collection collection = (Collection) o;
            if (exportExcel.template().length() != 0) {
                simpleExcel.exportTemplate(
                        collection,
                        exportExcel.name(),
                        exportExcel.template(),
                        exportExcel.templateStorageType(),
                        response);
            } else {
                if (collection.isEmpty()) {
                    simpleExcel.exportEmptyExcel(exportExcel.name(), response);
                } else {
                    Class<?> _class = CollUtil.get(collection, 0).getClass();
                    simpleExcel.exportExcel(collection, exportExcel.name(), _class, response);
                }
            }
        } else {
            throw new ResultException(StatusCode.UNKNOWN.getCode(), "方法返回值必须是Collection的子类");
        }
    }
}
